import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { ADD_USER, DELETE_USER, EDIT_USER, GET_USERS } from "../../api/userApi";

interface user {
  id: number;
  name: string;
  age: number;
}

const initialState: {
  users: user[];
  status: string;
  error: string;
} = {
  users: [],
  status: "idle",
  error: "",
};

export const getUsers = createAsyncThunk(
  "user/getUsers", // 异步 action 的名字，用于标识和调度
  async () => {
    // 异步函数，接收 url 和 thunkAPI 作为参数
    const res = await axios.get(GET_USERS); // 发起 GET 请求
    return res.data; // 返回数据，将作为 action.payload 传递到 reducer
  }
);

export const addUser = createAsyncThunk("user/addUser", async (user: user) => {
  const res = await axios.post(ADD_USER, user);
  return res.data;
});
export const updateUser = createAsyncThunk(
  "user/updateUser",
  async (params: { id: number; name: string; age: number }) => {
    const res = await axios.put(EDIT_USER + "/" + params.id, params);
    return res.data;
  }
);

export const deleteUser = createAsyncThunk(
  "user/deleteUser",
  async (params: { id: number }) => {
    const res = await axios.delete(DELETE_USER + "/" + params.id, {
      data: params,
    });
    return res.data;
  }
);

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {}, // 没有额外的同步 reducers，这部分留空
  extraReducers: (builder) => {
    // 处理异步操作的结果
    builder
      .addCase(getUsers.fulfilled, (state, action) => {
        console.log(action);
        state.users = action.payload.users;
        state.status = "success";
        state.error = "";
        console.log(state.users);
      })
      .addCase(getUsers.pending, (state, action) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(getUsers.rejected, (state, action) => {
        state.status = "failed";
        state.error = "获取用户数据失败";
      })
      .addCase(addUser.fulfilled, (state, action) => {
        state.users.push(action.payload.user);
        state.status = "success";
        state.error = "";
      })
      .addCase(addUser.pending, (state, action) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(addUser.rejected, (state, action) => {
        state.status = "failed";
        state.error = "添加用户失败";
      })
      .addCase(updateUser.fulfilled, (state, action) => {
        console.log(action);
        state.users = state.users.map((user) =>
          user.id === action.payload.user.id ? action.payload.user : user
        );
        state.status = "success";
        state.error = "";
      })
      .addCase(updateUser.pending, (state, action) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(updateUser.rejected, (state, action) => {
        state.status = "failed";
        state.error = "更新用户失败";
      })
      .addCase(deleteUser.fulfilled, (state, action) => {
        console.log(action);
        state.users.splice(0, 1);
        state.status = "success";
        state.error = "";
      })
      .addCase(deleteUser.pending, (state, action) => {
        state.status = "loading";
        state.error = "";
      })
      .addCase(deleteUser.rejected, (state, action) => {
        state.status = "failed";
        state.error = "删除用户失败";
      });
  },
});
